<template>
  <div class="video-list table-theme">
    <head-title title="营销--视频列表"></head-title>
    <el-card>
      <div class="top-menu">
        <div class="menu-left">
          <select-view
						:option-list="statusList"
						:value="status"
						placeholder="排序"
						type="status"
						@value="setSelectValue"
					>
					</select-view>
          <el-button type="primary" @click="OutVideo(2)">批量下架</el-button>
          <el-button type="primary" @click="OutVideo(1)">批量上架</el-button>
          <el-button type="primary" @click="DelVideo()">批量删除</el-button>
        </div>
        <div class="menu-right">
          <refresh-button @refresh="refreshPage"></refresh-button>
          <search-view
            :option="searchOption"
            @value="goSearch"
            @clear="refreshPage"
          ></search-view>
          <div class="add">
            <el-button type="primary" @click="openDialog('add')"
              >添加视频</el-button
            >
          </div>
        </div>
      </div>
      <p class="data-number">总数据数：{{ total }}</p>
      <el-table :data="list" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          label="序号"
          align="center"
          prop="video_id"
          width="80"
        ></el-table-column>
        <el-table-column label="视频" align="center">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              title=""
              trigger="hover"
              v-if="scope.row.link"
            >
              <video
                :src="scope.row.link"
                style="display: block; width: 300px"
                controls="controls"
              />
              <video
                slot="reference"
                :src="scope.row.link"
                style="width: 50px; height: 50px; vertical-align: top"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="封面" align="center" width="80">
          <template slot-scope="scope">
            <ImgPopover :src="scope.row.image"></ImgPopover>
          </template>
        </el-table-column>
        <el-table-column
          label="标题"
          align="center"
          prop="name"
        ></el-table-column>
        <el-table-column
          label="状态"
          align="center"
          prop="status_name"
          width="80"
        ></el-table-column>
        <el-table-column
          label="排序"
          align="center"
          prop="sort"
          width="80"
        ></el-table-column>
        <el-table-column
          label="添加时间"
          align="center"
          prop="add_time"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="openDialog(1, scope.row.video_id)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="DelVideo(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="init"
          :current-page="page"
        ></el-pagination>
      </div>
    </el-card>

    <el-dialog
      :title="infoForm.video_id?'编辑视频':'添加视频'"
      :visible.sync="is_Dialog"
      top="10vh"
      center
      :modal-append-to-body="false"
      width="680px"
      @close="onClose"
    >
      <el-form
        :model="infoForm"
        :rules="imageFormRules"
        ref="infoForm"
        label-width="80px"
      >
        <el-form-item label="标题:" prop="name">
          <el-input :disabled="is_disabled" v-model="infoForm.name"></el-input>
        </el-form-item>
        <el-form-item label="封面:" prop="image">
          <el-image
            :src="infoForm.image"
            v-if="is_disabled"
            fit="cover"
            style="height: 100px; width: 100px"
          ></el-image>
          <el-upload
            class="avatar-uploader"
            v-else
            ref="upload"
            action="fakeaction"
            :show-file-list="false"
            :http-request="
              function (res) {
                return upload(res);
              }
            "
            multipleaccept="image/*"
          >
            <img v-if="infoForm.image" :src="infoForm.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button
            type="danger"
            size="small"
            @click="reset('image')"
            v-if="infoForm.image && !is_disabled"
            >重置</el-button
          >
          <div class="el-upload__tip" v-if="!is_disabled">小于1MB</div>
        </el-form-item>
        <el-form-item label="视频:" prop="link">
          <video
            :src="infoForm.link"
            v-if="infoForm.link"
            controls
            autoplay
            height="150"
            width="100%"
          />
          <el-upload
            class="avatar-uploader"
            v-else
            ref="upload"
            action="fakeaction"
            :show-file-list="false"
            :http-request="
              function (res) {
                return uploadVideo(res);
              }
            "
            accept="video/mp4,avi"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button
            type="danger"
            v-if="infoForm.link && !is_disabled"
            size="small"
            @click="reset('video')"
            >重置</el-button
          >
          <div class="el-upload__tip" v-if="!is_disabled">小于20MB</div>
        </el-form-item>
        <el-form-item label="排序:" prop="sort">
          <el-input :disabled="is_disabled" v-model="infoForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-radio v-model="infoForm.status" :label="1">上架</el-radio>
          <el-radio v-model="infoForm.status" :label="2">下架</el-radio>
        </el-form-item>
				<el-form-item label="关联商品:">
					<el-button type="primary" size="mini" plain @click="glGoods">添加商品</el-button>
					<ul>
						<li v-for="(data,index) in goods_list" :key="index" style="display: flex; align-items: center;">
							<span>商品：{{data.goods_name}}</span><el-input placeholder="数量" v-model="data.number" size="mini" style="flex: 1; margin: 0 10px;"></el-input><em style="cursor: pointer; font-size: 20px; color: red;" class="el-icon-circle-close" @click="delGoods(index)"></em>
						</li>
					</ul>
				</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmClick('infoForm')"
          v-if="!is_disabled"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImgPopover from "@/components/ImgPopover";
import SelectView from "@/components/SelectView";
import goods from '@/components/layer-dialog/good-recommend.vue';
export default {
  components: {
    ImgPopover,
    SelectView,
		goods
  },
  data() {
    return {
      is_Dialog: false,
			goods_list: [],
      infoForm: {
        image: "",
        name: "",
        sort: 0,
        status: 1,
        link: "",
      },
      imageFormRules: {
        image: [{ required: true, message: "请上传封面" }],
        name: [{ required: true, message: "请填写标题" }],
        sort: [{ required: true, message: "请填写排序" }],
        status: [{ required: true, message: "请选择状态" }],
        link: [{ required: true, message: "请上传视频" }],
      },
      list: [],
      total: 0,
      status: 1,
      statusList: [
        {
          value: 1,
          label: "上架",
        },
        {
          value: 2,
          label: "下架",
        },
      ],
      page: 1,
      searchOption: [
        {
          value: 0,
          label: "序号",
        },
        {
          value: 1,
          label: "店铺ID",
        },
      ],
      classSelect: "",
      selectContent: "",
      store_id: "",
      type: "",
      is_disabled: false,
			multipleSelection: []
    };
  },
  methods: {
    handleSelectionChange(val) {
			if(val.length){
				console.log(val)
				val.forEach(item => {
					this.multipleSelection.push(item.video_id)
				})
			}else{
				this.multipleSelection = []
			}
    },
		OutVideo(type){
			if(!this.multipleSelection.length){
				return this.$layer.msg('请选择需要操作的数据')
			}
			this.$confirm('是否确定批量操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        this.$http(this.$ApiList.OutVideo,{video_id: this.multipleSelection.join(','),status: type}).then(res => {
          this.$layer.msg('操作成功')
					this.init()
        })
      }).catch(() => {});
		},
		DelVideo(data){
			if(!this.multipleSelection.length && !data){
				return this.$layer.msg('请选择需要操作的数据')
			}
			this.$confirm(!data?'是否确定批量操作?':'是否确定删除此视频?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        this.$http(this.$ApiList.DelVideo,{video_id: !data?this.multipleSelection.join(','):data.video_id}).then(res => {
          this.$layer.msg('删除成功')
					this.init()
        })
      }).catch(() => {});
		},
		glGoods(){
			this.$layer.iframe({
				title: "选择商品",
				maxmin: true,
				area: ["50%", "60%"],
				content: {
					content: goods, //传递的组件对象
					parent: this, //当前的vue对象
					data: {
						isVideo: true,
						// recommend_good: this.goods_list
					}, //props
				},
			});
		},
    // 初始化列表
    init(e) {
      this.page = e;
      let data = {
        page: e - 1 ? e - 1 : 0,
        limit: 10,
        status: this.status,
      };
      if (this.classSelect == 0) {
        data.video_id = this.selectContent;
      } else if (this.classSelect == 1) {
        data.store_id = this.selectContent;
      }
      if (this.store_id) {
        data.store_id = this.store_id;
      }
      this.$http(this.$ApiList.VideoList, data).then((res) => {
        this.list = res.datas.list;
        this.total = res.datas.count;
      });
    },
    goSearch(classSelect, selectContent) {
      this.classSelect = classSelect;
      this.selectContent = selectContent;
      this.init(1);
    },
    refreshPage() {
      this.page = 1;
      this.status = 1;
      this.selectContent = "";
      this.classSelect = 0;
      this.init();
    },
    upload(params) {
      const file = params.file,
        isJPGPNG = file.type === "image/jpeg" || "image/png",
        isLt1MB = file.size / 1024 <= 10240;
      if (!isJPGPNG) {
        this.$message.error("只能上传图片格式png、jpg!");
        return;
      }
      if (!isLt1MB) {
        this.$message.error("图片不能大于10M");
        return;
      }

      let image = new FormData();
      image.append("file[]", file);

      this.$http(this.$ApiList.publicUpload, image).then((res) => {
        this.infoForm.image = res.datas[0];
      });
    },
    // 上传视频
    uploadVideo(params) {
      const file = params.file,
        isLt20MB = file.size / 1024 / 1024 < 20;
      if (!isLt20MB) {
        this.$message.error("视频不能大于20MB!");
        return;
      }
      const form = new FormData();
      form.append("file[]", file);
      this.$http(this.$ApiList.UpVideo, form).then((res) => {
        this.infoForm.link = res.datas;
      });
    },
    // 重置
    reset(type) {
      if (type === "image") {
        this.infoForm.image = "";
      } else if (type === "video") {
        this.infoForm.link = "";
      }
    },
    //提交
    confirmClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
					let postData = {
						video_id: this.infoForm.video_id,
						image: this.infoForm.image,
						name: this.infoForm.name,
						sort: this.infoForm.sort,
						status: this.infoForm.status,
						link: this.infoForm.link,
						goods_list: ''
					}
					if(this.goods_list.length){
						let arr = []
						this.goods_list.forEach(item => {
							arr.push({
								goods_id: item.goods_id,
								num: item.number,
							})
						})
						postData.goods_list = JSON.stringify(arr)
					}
					if(this.infoForm.video_id){
						this.$http(this.$ApiList.editVideo, postData).then((res) => {
							if(res.code==200){
								this.$layer.msg(res.datas);
								this.init()
								this.$refs[formName].resetFields();
								this.goods_list = []
								this.is_Dialog = false
							}
						});
					}else{
						this.$http(this.$ApiList.AddVideo, postData).then((res) => {
							if(res.code==200){
								this.$layer.msg(res.datas);
								this.init()
								this.$refs[formName].resetFields();
								this.goods_list = []
								this.is_Dialog = false
							}
						});
					}
        } else {
          this.$layer.msg("请填写完整信息后提交");
        }
      });
    },
    // 弹窗
    openDialog(type, video_id) {
      this.type = type;
			if(type==1){
				this.$http(this.$ApiList.VideoInfo, { video_id }).then((res) => {
					this.infoForm = res.datas;
					res.datas.goods_list.forEach(item => {
						item.number = item.num
					})
					this.goods_list = res.datas.goods_list
				});
			}
      this.is_Dialog = true;
    },
    // 关闭弹窗
    onClose() {
      this.is_Dialog = false;
      this.$refs["infoForm"].resetFields();
      this.infoForm = {
        image: "",
        name: "",
        sort: 0,
        status: 1,
        link: "",
      };
    },
    setSelectValue(obj) {
      const { type, value } = obj;
      switch (type) {
        case "status":
          this.status = value;
          break;

        default:
          break;
      }
      this.init();
    },
		setGoodsId(goods) {
			goods.forEach(item => {
				item.number = 1
			})
			this.goods_list = goods
    },
		delGoods(index){
			this.goods_list.splice(index,1)
		}
  },
  created() {
    if (this.$route.query.store_id) {
      this.store_id = this.$route.query.store_id;
      this.searchOption = [
        {
          value: 0,
          label: "序号",
        },
      ];
    }
    this.init();
  },
};
</script>
<style lang="scss">
.video-list {
}
</style>
